package hibernateDAOS;

import hibernate.HibernateUtil;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;


import beans.ItemReceta;
import beans.Receta;

public class RecetaDAO {
	
	private static RecetaDAO instancia = null;
	private static SessionFactory sf = null;

	public static RecetaDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new RecetaDAO();
		} 
		return instancia;
	}
	
	public void guardarReceta(Receta r){
		Session session = sf.openSession();
		session.beginTransaction();
		session.save(r);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}

	public void eliminarReceta(Receta r){
		Session session = sf.openSession();
		session.beginTransaction();
		session.delete(r);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}

	public void modificarReceta(Receta r){
		Session session = sf.openSession();
		session.beginTransaction();
		session.saveOrUpdate(r);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}

	@SuppressWarnings("unchecked")
	public List<Receta> obtenerRecetas(){
		Session session = sf.openSession();
		Query q = session.createQuery("from Recetas");
		List<Receta> recetas = q.list();
		session.close();
		return recetas;
	}
	
	public List<Object[]> obtenerRecetasObject() throws RemoteException
	{
		Session session = sf.openSession();
		Query q = session.createQuery("from Receta");
		List<Receta> recetas = q.list();
		session.close();
		List<Object[]> os = new ArrayList<Object[]>();
		Object[] o ;
		int cant=0;
		for(Receta r : recetas){
			o = new Object[recetas.size()];
			o[0] = r.getIdReceta();
			o[1] = r.getNombreReceta();
//			int i = 0;
//			for (ItemReceta ir : r.getIngredientes()) 
//			{
//				
//				Object[] oo = new Object[r.getIngredientes().size()];
//				oo[i] = ir.getProducto();
//				
//			}
			os.add(o);
		}
		return os;
	}
	
	public Receta obtenerRecetaXId (Integer id) throws RemoteException
	{
		Session session = sf.openSession();
		Query q = session.createQuery("from Receta where idReceta = :id").setParameter("id", id);
		Receta receta = (Receta) q.uniqueResult();
		session.close();
		return receta;
	}
}
